<?php

namespace app\api\model\mine;

use app\api\model\BaseModel;
use app\api\model\common\CoinModel;
use app\api\model\order\OrderMiningModel;
use think\Exception;

class ComputingPowerModel extends BaseModel
{
    protected $name = 'computing_power';

    /**
     * Notes: 每小时算力浮动计算
     * User: cyy
     * Date: 2023/12/7 20:42
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function range(): bool
    {
        $min_mange = config('site.min_range');
        $max_mange = config('site.max_range');


        $time = time();
        $date = date('Y-m-d', $time);
        $hour = date('H', $time);


        $orderModel = new OrderMiningModel();
        $coinModel = new CoinModel();

        $coinList = $coinModel->field('id,coin_type')->select();

        $sta_time = strtotime(date('Y-m-d'));
        $end_time = $sta_time + 86399;
        $this->startTrans();
        try {
            foreach ($coinList as $item) {
                $orderList = $orderModel->where('coin_id', $item['id'])
                    ->where('status', OrderMiningModel::STATUS_PAY)
                    ->where('create_time', 'not in', [$sta_time, $end_time])
                    ->group('user_id')->select();

                if (count($orderList) > 0) {
                    foreach ($orderList as $value) {
                        if (!$this->where(['coin_id' => $item['id'], 'date' => $date, 'hour' => $hour, 'user_id' => $value['user_id']])->count()) {
                            $range = rand($min_mange, $max_mange);

                            $this->insert([
                                'user_id' => $value['user_id'],
                                'coin_id' => $item['id'],
                                'coin_type' => $item['coin_type'],
                                'date' => $date,
                                'hour' => $hour,
                                'range' => round($range / 100, 2),
                                'create_time' => $time,
                                'update_time' => $time,
                            ]);
                        }
                    }
                }
            }
            $this->commit();
        } catch (Exception $exception) {
            dump($exception->getMessage());
            $this->rollback();
            return false;
        }

        return true;

    }
}